package com.econvent.common.conn;

import com.econvent.common.conn.config.BaseConfig;
import com.econvent.common.conn.config.HikariCpConfig;
import com.econvent.common.conn.entity.BaseDataSourceProperty;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class HikariCpDataSourceBuilder extends DataSourceBuilder {
    @Override
    public void buildDataSource(BaseDataSourceProperty baseDataSourceProperty) {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setUsername(baseDataSourceProperty.getUser());
        hikariDataSource.setPassword(baseDataSourceProperty.getPassword());
        hikariDataSource.setJdbcUrl(baseDataSourceProperty.getUrl());
        hikariDataSource.setPoolName(baseDataSourceProperty.getDatasourcename());

        String driverClassName = baseDataSourceProperty.getDriverName();
        if (StringUtils.isNoneBlank(driverClassName)) {
            hikariDataSource.setDriverClassName(driverClassName);
        }
    }

    @Override
    public void buildDataSourceConfig(BaseConfig dataSourceConfig) {
        HikariCpConfig hikariCpConfig = (HikariCpConfig)dataSourceConfig ;

        HikariConfig config =  new HikariConfig() ;
        try {
            BeanUtils.copyProperties(config, hikariCpConfig);

            // 设置属性
            ((HikariDataSource)dataSource).copyStateTo(config);
        } catch (Exception e) {
            log.error("DruidDataSourceBuilder buildDataSourceConfig error, the exception is {} ", e);
            return  ;
        }
    }
}
